package com.onec.service.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyDiscardServer {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private final int serverPart;

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    public NettyDiscardServer() {
        serverPart = 10089;
    }

    public void runServer() {
        EventLoopGroup boosLoopGroup = new NioEventLoopGroup(1);

        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            // 设置反应轮询器的组
            serverBootstrap.group(boosLoopGroup, workerLoopGroup);
            // 设置nio 类型的通道
            serverBootstrap.channel(NioServerSocketChannel.class);
            // 设置监听端口
            serverBootstrap.localAddress(serverPart);
            // 设置通道参数
            serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            // 装配子通道流水线
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new NettyDisCardHandler());
                }
            });

            // sync 方法阻塞 知道绑定更成功
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            logger.info("服务启动成功，监听端口：{}", channelFuture.channel().localAddress());
            // 等待通道关闭的异步任务结束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();

            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerLoopGroup.shutdownGracefully();
            boosLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyDiscardServer().runServer();
    }
}

